package com.cy.pj.goods.dao;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;

import javax.sql.DataSource;
import java.sql.*;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Repository
public class DefaultGoodsDao implements GoodsDao {

    @Autowired
    private DataSource dataSource;

    private static final Logger log = LoggerFactory.getLogger(DefaultGoodsDao.class);


    Map<String,Object> rowMap(ResultSetMetaData rsmd, ResultSet rs) throws SQLException {
        Map<String,Object> map = new HashMap<>();
        for (int i = 1; i < rsmd.getColumnCount(); i++) {
            map.put(rsmd.getColumnName(i), rs.getObject(rsmd.getColumnName(i)));
        }
        return map;
    }


    @Override
    public List<Map<String, Object>> findgoods() {
        Connection conn = null;
        Statement stmt = null;
        ResultSet rs = null;
        try {
            conn = dataSource.getConnection();
            stmt = conn.createStatement();
            String sql = "select * from tb_goods";
            rs = stmt.executeQuery(sql);
            List<Map<String, Object>> list = new ArrayList<>();
            ResultSetMetaData rsmd = rs.getMetaData();
            while (rs.next()) {
//                HashMap map = new HashMap();
//                map.put("id", rs.getInt("id"));
//                map.put("name", rs.getString("name"));
//                map.put("remark", rs.getString("remark"));
//                map.put("createdTime", rs.getTimestamp("createdTime"));
//                list.add(map);
                list.add(rowMap(rsmd, rs));
            }
            return list;
        } catch (SQLException e) {
//            e.printStackTrace();
//            return null;
            log.error("查询错误,{}"+e.getMessage());
            throw new RuntimeException("数据查询失败"+e.getMessage());
        } finally {
           close(rs, stmt, conn);
        }
    }
    private void close(ResultSet rs, Statement stmt, Connection conn){
        if (rs != null) try {rs.close();} catch (Exception e) {}
        if (stmt != null) try {stmt.close();} catch (Exception e) {}
        if (conn != null) try {conn.close();} catch (Exception e) {}
    }
}
